package cn.jbolt.meinvtu.robot;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

import cn.jbolt.meinvtu.album.AlbumService;
import cn.jbolt.meinvtu.common.model.Album;
import cn.jbolt.meinvtu.common.model.Meinv;
import cn.jbolt.meinvtu.common.model.Photo;
import cn.jbolt.meinvtu.photo.PhotoService;

public class RobotService {
	@Inject
	private AlbumService albumService;
	@Inject
	private PhotoService photoService;
	/**
	 * 开始执行羞羞的事情
	 * @return
	 */
	public Ret startCrawling(Integer meinvId) {
		if(meinvId==null||meinvId<=0){
			return Ret.fail("msg","我是谁？我TM在哪儿？");
		}
		Meinv meinv=Meinv.dao.findById(meinvId);
		if(meinv==null){
			return Ret.fail("msg","我是谁？我TM在哪儿？");
		}
		if(StrKit.isBlank(meinv.getUrl())){
			return Ret.fail("msg","【"+meinv.getName()+"】的数据异常，抓不了！");
		}
		albumService.deleteByMeinvId(meinvId);
		photoService.deleteByMeinvId(meinvId);
		String url=meinv.getUrl();
		Document document =null;
		try {
			document= Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36").ignoreHttpErrors(true).ignoreContentType(true).timeout(10000).get();
		} catch (IOException e) {
			e.printStackTrace();
			return Ret.fail("msg", "抓取相册主页失败");
		}
		if(document==null){
			return Ret.fail("msg", "未抓取到相册数据1");
		}
		//更新美女信息
		updateMeinv(meinv,document);
		//得到相册列表
		List<Album> albums=crawlingAlbums(document,meinvId);
		if(albums==null||albums.size()==0){
			return Ret.fail("msg", "未抓取到相册数据2");
		}
		//先存数据库里
		Db.batchSave(albums, albums.size());
		//最后执行获取照片的任务
		Ret ret=crawlingPhotos(meinvId);
		if(ret.isOk()){
			return ret.set("avatar", meinv.getAvatar());
		}
		return ret;
	}
	/**
	 * 更新美女信息
	 * @param meinv
	 * @param document
	 */
	private void updateMeinv(Meinv meinv, Document document) {
		//得到美女头像和简介
		String avatar=crawlingMeinvAvatar(document);
		if(StrKit.notBlank(avatar)){
			meinv.setAvatar(avatar);
		}
		String content=crawlingMeinvContent(document);
		if(StrKit.notBlank(content)){
			meinv.setContent(content);
		}
		//更新
		meinv.update();
		
	}
	/**
	 * 得到美女头像
	 * @param document
	 * @return
	 */
	private String crawlingMeinvAvatar(Document document) {
		Element img=document.selectFirst("div.intro_cont > div > div.intro_img > img");
		if(img!=null){
			return img.attr("src");
		}
		return null;
	}
	/**
	 * 得到美女简介
	 * @param document
	 * @return
	 */
	private String crawlingMeinvContent(Document document) {
		Element content=document.selectFirst("div.intro_cont > div > div.intro_p > p");
		if(content!=null){
			return content.text();
		}
		return null;
	}
	/**
	 * 获取照片
	 * @return
	 */
	private Ret crawlingPhotos(Integer meinvId) {
		List<Album> albums=albumService.getMeinvAlbums(meinvId);
		if(albums==null||albums.size()==0){
			return Ret.fail("msg","尚无相册信息，不能抓取照片");
		}
		for(Album album:albums){
			crawlingOneAlbumPhoto(album);
		}
		return Ret.ok("msg","抓取成功");
	}

	/**
	 * 抓取一个相册中的照片
	 * @param album
	 */
	private void crawlingOneAlbumPhoto(Album album) {
		String url=album.getUrl();
		Document document =null;
		try {
			document= Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36").ignoreHttpErrors(true).ignoreContentType(true).timeout(10000).get();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(document!=null){
			Element totalCountEle=document.select("div.pic_main > div > div.Bigimg > div.ptitle > em").last();
			String totalCountStr=totalCountEle.text().trim();
			int count=Integer.parseInt(totalCountStr);
			List<Photo> photos=new ArrayList<Photo>();
			for(int i=1;i<=count;i++){
				List<Photo> temps=crawlingOneAlbunPhotoByPage(album,i);
				if(temps!=null&&temps.size()>0){
					photos.addAll(temps);
				}
			}
			if(photos.size()>0){
				Db.batchSave(photos, photos.size());
				album.setCount(photos.size());
				album.update();
			}
		}
	}

	private List<Photo> crawlingOneAlbunPhotoByPage(Album album, int i) {
		String url=album.getUrl().replace(".html", "_")+i+".html";
		Document document =null;
		try {
			document= Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36").ignoreHttpErrors(true).ignoreContentType(true).timeout(10000).get();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(document!=null){
			Elements imgs=document.select("img.pic-large");
			if(imgs!=null&&imgs.size()>0){
				List<Photo> photos=new ArrayList<Photo>();
				for(Element img:imgs){
					photos.add(processOnePhoto(album.getId(),album.getMeinvId(),img));
				}
				return photos;
			}
		}
		return null;
	}

	private Photo processOnePhoto(Integer albumId,Integer meinvId, Element img) {
		Photo photo=new Photo();
		photo.setAlbumId(albumId);
		photo.setCreateTime(new Date());
		photo.setMeinvId(meinvId);
		photo.setUrl(img.dataset().get("original"));
		photo.setName(photo.getUrl());
		return photo;
	}
	/**
	 * 解析出相册列表
	 * @param document
	 * @param meinvId 
	 * @return
	 */
	private List<Album> crawlingAlbums(Document document, Integer meinvId) {
		//找到相册列表
		Element ul=document.selectFirst(".Left_bar .tab_box ul");
		Elements lis=ul.children();
		if(lis==null||lis.size()==0){
			return null;
		}
		 List<Album> albums=new ArrayList<Album>();
		for(Element li:lis){
			//循环处理每一个相册
			albums.add(processOneAlbum(li,meinvId));
		}
		return albums;
	}

	private Album processOneAlbum(Element li, Integer meinvId) {
		Element img=li.selectFirst("img");//找相册封面
		Element link=li.selectFirst("a");//找相册内页链接
		Album album=new Album();
		album.setUrl(link.absUrl("href"));
		album.setName(img.attr("alt"));
		album.setCount(0);
		album.setMeinvId(meinvId);
		album.setCreateTime(new Date());
		album.setPost(img.absUrl("src"));
		return album;
	}
}
